  <template>
    <div class="app-container">
      <el-row :gutter="20">
        <!--部门数据-->
        <el-col :span="deptSpan" :xs="24">
          <div class="head-container">
            <el-input
              v-model="deptName"
              placeholder="请输入部门名称"
              clearable
              size="small"
              prefix-icon="el-icon-search"
              style="margin-bottom: 20px;"
              maxlength="30"
            />
          </div>
          <div class="head-container">
            <el-tree
              :data="deptOptions"
              :props="defaultProps"
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
              ref="tree"
              node-key="id"
              default-expand-all
              highlight-current
              @node-click="handleNodeClick"
            />
          </div>
        </el-col>
        <!--订单数据-->
        <el-col :span="orderListSpan" :xs="24">
          <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="订单号" prop="orderNo">
              <el-input
                v-model="queryParams.orderNo"
                placeholder="请输入订单号"
                maxlength="50"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="订单状态" prop="orderState">
              <el-select v-model="queryParams.orderState" placeholder="订单状态" clearable>
                <el-option
                  v-for="dict in dict.type.order_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="商品名" prop="productName">
              <el-input
                v-model="queryParams.productName"
                placeholder="请输入商品名"
                maxlength="50"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>

            <el-form-item label="下单人" prop="userName">
              <el-input
                v-model="queryParams.userName"
                placeholder="请输入下单人"
                maxlength="10"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>

          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button
                type="primary"
                plain
                icon="el-icon-printer"
                size="mini"
                :disabled="multiple"
                @click="handleUpdateOrderState('', '2')"
                v-hasPermi="['order:search:accept']"
              >接单</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="success"
                plain
                icon="el-icon-loading"
                size="mini"
                :disabled="multiple"
                @click="handleUpdateOrderState('', '3')"
                v-hasPermi="['order:search:production']"
              >投产</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="danger"
                plain
                icon="el-icon-s-claim"
                size="mini"
                :disabled="multiple"
                @click="handleUpdateOrderState('', '4')"
                v-hasPermi="['order:search:complete']"
              >完成</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="warning"
                plain
                icon="el-icon-truck"
                size="mini"
                :disabled="multiple"
                @click="handleUpdateOrderState('', '5')"
                v-hasPermi="['order:search:deliver']"
              >发货</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
          </el-row>

          <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="序号" align="center" prop="uuid" width="100" />
            <el-table-column label="订单号" align="center" prop="orderNo" :show-overflow-tooltip="true"/>
            <el-table-column label="订单状态" align="center" prop="orderState" :show-overflow-tooltip="true" width="80">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.order_status" :value="scope.row.orderState"/>
            </template>
            </el-table-column>
            <el-table-column label="商品名" align="center" prop="productName" :show-overflow-tooltip="true"/>
            <el-table-column label="数量 / 件" align="right" prop="number" width="100" >
            <template slot-scope="scope">
                <span>{{ numberToCurrencyNo(scope.row.number) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="合同额 / 元" align="right" prop="amount" width="100" >
              <template slot-scope="scope">
                <span>{{ numberToCurrencyNo(scope.row.amount) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="下单时间" align="center" prop="orderTime" width="100">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.orderTime, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>
            <el-table-column label="下单人" align="center" prop="userName" width="100" />
            <el-table-column label="附件" align="center" width="150" >
            <template slot-scope="scope">
              <el-link v-for="(item, index) in scope.row.file" :key="item.fileId" @click="downloadOrderExcel(item.fileId, index + 1, scope.row.orderNo, scope.row.file.length)"
               style="display: block;" icon="el-icon-paperclip">{{item.fileName}}</el-link>
            </template>
          </el-table-column>
          <el-table-column label="预计交货期" align="center" prop="deliveryTime" width="100">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.deliveryTime, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleUpdate(scope.row)"
                  v-hasPermi="['order:search:edit']"
                >修改</el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row)"
                  v-hasPermi="['order:search:remove']"
                >删除</el-button>
                <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)" v-hasPermi="['order:search:repair', 'order:search:repair']">
                  <el-button size="mini" type="text" icon="el-icon-d-arrow-right">更多</el-button>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item command="accept" icon="el-icon-printer" v-if="scope.row.orderState === '1'"
                      v-hasPermi="['order:search:accept']">接单</el-dropdown-item>
                    <el-dropdown-item command="production" icon="el-icon-loading" v-if="scope.row.orderState === '2'"
                      v-hasPermi="['order:search:production']">投产</el-dropdown-item>
                    <el-dropdown-item command="complete" icon="el-icon-s-claim" v-if="scope.row.orderState === '3'"
                      v-hasPermi="['order:search:complete']">完成</el-dropdown-item>
                    <el-dropdown-item command="deliver" icon="el-icon-truck" v-if="scope.row.orderState === '4'"
                      v-hasPermi="['order:search:deliver']">发货</el-dropdown-item>
                    <el-dropdown-item command="repair" icon="el-icon-refresh-left" v-if="scope.row.orderState === '5'"
                      v-hasPermi="['order:search:repair']">返修</el-dropdown-item>
                    <el-dropdown-item command="cancel" icon="el-icon-refresh-right"
                      v-hasPermi="['order:search:cancel']">取消</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </template>
            </el-table-column>
          </el-table>
      
          <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
          />
        </el-col>
      </el-row>

      <el-dialog 
        :title="title" 
        :visible.sync="open" 
        :close-on-click-modal="false" 
        width="1000px">
        <order-form :orderBaseInfo="orderBaseInfo" :inOrderInfo="orderInfo" @closeDialog="closeDialog" @confrimDialog="confrimDialog"></order-form>    
      </el-dialog>
    </div>
  </template>
  
  <script>

  import { listOrder, getOrder, updateOrderState, deleteOrder } from "@/api/order/search/search";
  import { deptTreeSelectByRole } from "@/api/system/user";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  import orderForm from "@/components/order";

  export default {
    components: {
      orderForm
    },
    dicts: ['order_status'],
    data() {
      return {
        deptSpan: 0,
        orderListSpan : 24,
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 公告表格数据
        orderList: [],
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          orderNo: undefined,
          orderState: undefined, 
          userName: undefined,
          productName: undefined,
          deptId: undefined
        },
        // 表单参数
        form: {},
        // 部门树选项
        deptOptions: undefined,
        // 部门名称
        deptName: undefined,
        defaultProps: {
          children: "children",
          label: "label"
        },
        // 标题
        title: "",
        // 表单校验
        rules: {
        },
        // 寄件人信息
        orderBaseInfo:{
          sendName:"测试1",
          sendPhone:"15940851234",
          sendAddress:"花果山水帘洞9587号猴子",
          id:""
        },
        // 表单参数
        orderInfo:{
          contactName:"",
          contactPhone:"",
          contactAddress:"",
          zipCode:"",
          orderType:"",
          deliveryTime:"",
          children:[]
        },  
      };
    },
    watch: {
      // 根据名称筛选部门树
      deptName(val) {
        this.$refs.tree.filter(val);
      }
    },
    created() {
      this.getList();
      this.getDeptTree();
    },
    methods: {
      /** 查询订单列表 */
      getList() {
        this.loading = true;
        listOrder(this.queryParams).then(response => {
          this.orderList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      
      /** 查询部门下拉树结构 */
      getDeptTree() {
        deptTreeSelectByRole().then(response => {
          this.deptOptions = response.data;
          if (response.data.length === 0) {
            this.deptSpan = 0;
            this.orderListSpan = 24;
          } else {
            this.deptSpan = 4;
            this.orderListSpan = 20;
          }
        });
      },

      /** 筛选节点 */
      filterNode(value, data) {
        if (!value) return true;
        return data.label.indexOf(value) !== -1;
      },

      /** 节点单击事件 */
      handleNodeClick(data) {
        this.queryParams.deptId = data.id;
        this.handleQuery();
      },

      /** 取消按钮 */ 
      cancel() {
        this.open = false;
        this.reset();
      },

      /** 表单重置 */ 
      reset() {
        this.form = {
          deptId: undefined,
          orderNo: undefined,
          orderState: "0",
          userName: undefined,
          productName: undefined
        };
        this.resetForm("form");
      },

      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },

      /** 重置按钮操作 */
      resetQuery() {
        this.queryParams.deptId = undefined;
        this.$refs.tree.setCurrentKey(null);
        this.resetForm("queryForm");
        this.handleQuery();
      },

      /** 多选框选中数据 */ 
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.uuid);
        this.single = selection.length != 1;
        this.multiple = !selection.length;
      },

      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const orderId = row.uuid || this.ids
        getOrder(orderId).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "订单修改";
        });
      },

      /** 订单修改页面取消 */
      closeDialog() {
        this.open = false;      
      },

      /** 订单修改页面确定 */
      confrimDialog(orderInfo, upFileList) {
        this.open = false;   
      },

      /** 删除按钮操作 */
      handleDelete(row) {
        const orderIds = row.uuid || this.ids;
        this.$modal.confirm('是否确认删除序号为"' + orderIds + '"的数据项？').then(function() {
          return deleteOrder(orderIds);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },

      /** 删除按钮操作 */
      handleCancel(row) {
        const orderIds = row.uuid || this.ids;
        this.$modal.confirm('是否确认取消序号为"' + orderIds + '"的数据项？').then(function() {
          return deleteOrder(orderIds);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("取消成功");
        }).catch(() => {});
      },

      /** 更多操作触发 */
      handleCommand(command, row) {
        switch (command) {
          case "accept":
            // 接单
            this.handleUpdateOrderState(row, '2');
            break;
          case "production":
            // 投产
            this.handleUpdateOrderState(row, '3');
            break;
          case "complete":
            // 完成
            this.handleUpdateOrderState(row, '4');
            break;
          case "deliver":
            // 发货
            this.handleUpdateOrderState(row, '5');
            break;
          case "repair":
            // 返修
            this.handleRepair(row);
            break;
          case "cancel":
            // 取消
            this.handleCancel(row);
            break;
          default:
            break;
        }
      },

      /** 接单 */ 
      handleUpdateOrderState(row, model) {
        const orderIds = row.uuid || this.ids;
        let confirmMsg = "";
        let successMsg = "";
        switch (model) {
          case "2":
            // 接单
            confirmMsg = '确认将序号为"' + orderIds + '"的数据进行接单？';
            successMsg = '接单成功';
            break;
          case "3":
            // 投产
            confirmMsg = '确认将序号为"' + orderIds + '"的数据进行投产？';
            successMsg = '投产成功';
            break;
          case "4":
            // 完成
            confirmMsg = '确认序号为"' + orderIds + '"的数据已经生产完成？';
            successMsg = '生产完成';
            break;
          case "5":
            // 发货
            confirmMsg = '确认将序号为"' + orderIds + '"的数据进行发货？';
            successMsg = '发货成功';
            break;
          default:
            break;
        }

        this.$modal.confirm(confirmMsg).then(function() {
          return updateOrderState(orderIds, model);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess(successMsg);
        }).catch(() => {});
      },

      /** 返修 */ 
      handleRepair(row) {

      },

      /** 下载订单文件 */
      downloadOrderExcel(fileId, index, orderNo, fileLength) {
        let fileName = "";
        if (fileLength === 1) {
          fileName = orderNo + '.xlsx';
        } else {
          fileName = orderNo + '_' + index + '.xlsx';
        }

        this.download('order/download/' + fileId, {
        }, fileName)
      },
      
      /** 提交按钮 */
      submitForm: function() {

      },

      /** 添加千位分隔符 */
      numberToCurrencyNo(value) {
        if (!value) return 0;
        // 获取整数部分
        const intPart = Math.trunc(value);
        // 整数部分处理，增加,
        const intPartFormat = intPart.toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,');
        // 预定义小数部分
        let floatPart = '';
        // 将数值截取为小数部分和整数部分
        const valueArray = value.toString().split('.');
        if (valueArray.length === 2) {
          // 有小数部分, 取得小数部分
          floatPart = valueArray[1].toString() ;
          return intPartFormat + '.' + floatPart;
        }
        return intPartFormat + floatPart;
      }
    }
  };
  </script>
  
